<template>
	<div class="FeaturedGoodsNew">
		<!-- 先注释掉等后台加字段 -->
		<div class="versionButtonGropu">
			<blue-button :text="'新增版本'" :clickEvent="addVersion"></blue-button>
			<blue-button :text="'编辑'" :clickEvent="editVersion"></blue-button>
			<div @click="deleteVersion"  :style="isGrayDis?'pointer-events: none;':'cursor:pointer'">
				<span class="deleteSpan" :style="isGrayDis?'background: #999;border:1px solid #999':''">删除</span>
			</div>
			<!-- <blue-button :text="'删除'" :clickEvent="deleteVersion"></blue-button> -->
		</div>
		<div class="versionBox" >
			<div class="versionName" 
				v-for="(item,index) in versionArray" :key="index"  
				@click="clickVersionName(item,index)" 
				:class="{'versionBg':indexNum===index,'currentItem':item.show===1}"
				:data-currentItem="item.show"
				:data-rid="item.rid"
				ref= "versionSpecial" >
				<span>{{item.titleName}}</span>
			</div>
		</div>

		<div>
			<blue-button :text="'新增'" :clickEvent="clickAdd" style="text-align:left"></blue-button>
			<table class="sv-table">
					<tr class="table-th">
						<th>资源位</th>
						<th>资源图片</th>
						<th>配置路径</th>
						<th>更新日期</th>
						<th>操作</th>
					</tr>
					<tr class="table-tr" v-for="(item,index) in myDateList" :key="index">
						<td>{{index+1}}</td>
						<td style=""><img :src="item.publicityPicture" /></td>
						<td>{{urlfn(item.extendField)}}</td>
						<td>{{item.updateTm?myGetTime(item.updateTm):myGetTime(item.createTm)}}</td>
						<td style="text-align: center;">
							<gray-button class="grayBtn" :text="'更新'" :clickEvent="clickEdit.bind(this, index,item)"></gray-button>
							<gray-button class="grayBtn" :text="'删除'" :clickEvent="deleteGoods.bind(this, item)"></gray-button>
						</td>
					</tr>
				</table>
		</div>
		<edit-model ref="editModel" title="自定义产品菜单">
			<div class="slot-banner" slot="main">
				<div>
					<p class="eidt-slot-title">宣传图片<span class="required">*</span></p>
					<div class="upload-box">
						<img-upload :deleteCallback="deleteImgCallback" ref="bannerImg" :imgShowList="getBannerUrl ? [getBannerUrl] : []">
						</img-upload>
					</div>
				</div>
				<div>
					<p class="eidt-slot-title" style="width: 23%;">自定义跳转链接</p>
					<page-path :changeEvent="changeEvent" :defaultChooseProps="valueArray" rootSelector="#edit-model-box"></page-path>
				</div>
				<div class="fabu-box">
					<blue-button text="发布" :clickEvent="upLoadImg"></blue-button>
					<gray-button text="取消" :clickEvent="hideModel" class="confimBtn"></gray-button>
				</div>
			</div>
		</edit-model>
		<!-- 先注释掉等后台加字段 -->
		<edit-model ref="versionModel" title="自定义版本">
			<div class="slot-banner" slot="main">
					<div class="version-item version-item-first">
						<span class="eidt-slot-title">版本名称<span class="required">*</span></span>
						<input type="text" v-model="getDataItem.titleName"/>
					</div>
					<div class="version-item">
						<span class="eidt-slot-title">生效时间<span class="required">*</span></span>
						<el-date-picker  v-model="startTime" type="datetime" placeholder="选择日期时间" style="border: none;width: 350px;margin-left:10px">
						</el-date-picker>
					</div>
					<div class="version-item">
						<span class="eidt-slot-title">失效时间<span class="required">*</span></span>
						<el-date-picker  v-model="endTime" type="datetime" placeholder="选择日期时间" style="border: none;width: 350px;margin-left:10px">
						</el-date-picker>
					</div>
					<div class="fabu-box">
						<blue-button text="提交" :clickEvent="versionPublish"></blue-button>
						<gray-button text="取消" :clickEvent="cancelVerionPub" class="confimBtn"></gray-button>
					</div>
			</div>
		</edit-model>
		<m-toast ref="toast"></m-toast>
		<m-dialog ref="dialog"></m-dialog>
	</div>

</template>

<script>
	import BlueButton from "../../edit-components/BlueButton";
	import getDate from "./getGoodsDate.js";
	import madd from "./add.js";
	import medit from "./edit.js";
	import deleteGoods from './delete.js';
	import GrayButton from "../../edit-components/GrayButton";
	import imgUpload from "../../real-components/ImgUpload2";
	import EditModel from "../../edit-components/EditModel";
	import Toast from "../../edit-components/Toast";
	import Dialog from "../../edit-components/Dialog";
	import PagePath from "../../edit-components/PagePath";
	import { DatePicker } from "element-ui";
	import addVersionRes from "./addVersion";
	import editVersionRes from "./editVersion";
	import deleteVersionRes from "./deleteVersion";
	import getVersionDataList from "./getVersionData"
	import { mapGetters ,mapMutations} from "vuex";


	export default {
		props: {
			config:{
				type:Object,
				default: ()=>{}
			}
		},
		data() {
			return {
				dataList: [],
				imgUrl: '', //图片地址信息 
				uploadType: '',
				dataListSinger: {},
				getBannerUrl: null,
				ziyuanwei: null,
				editItem: null,
				//跳转路径配置二级联动（数据模拟）
				selected: "",
				//获取门店数据
				storeCode: "",
				valueArray:[],
				startTime:'',//生效时间
				endTime:'',//失效时间
				titleName:'',//版本名称
				versionType:'add',//初始化版本类型(add edit)
				versionArray:[],
				indexNum:'',
				versionDataItem:{},//版本信息的初始化
				isInit:false,
				initRid :'',
				isGrayDis:false
			}
		},
		components: {
			"blue-button": BlueButton,
			"gray-button": GrayButton,
			"img-upload": imgUpload,
			"edit-model": EditModel,
			"m-toast": Toast,
			"m-dialog": Dialog,
			"page-path": PagePath,
			"el-date-picker": DatePicker,
		},
		computed: {
			...mapGetters("lxn", ["getclickVersionIndex"]),
			myDateList() {
				return this.dataList;
			},
            relGroup(){
				return this.config.id
			},
			getDataItem(){
				if(this.versionDataItem) {
					return this.versionDataItem;
				}
				return {};
			}
		},

		methods: {
			...mapMutations('lxn', [
				"setclickVersionIndex"
			]),
			//获取门店code
			getShopCode() {
				this.storeCode = localStorage.getItem("storeCode");
			},
			//获取子组件路径的值
			changeEvent(data) {
				this.selected = data
			},
			//路径地址展示
			urlfn(item) {
				if(JSON.parse(item).url){
					return JSON.parse(item).url.UIContent
				}else{
					return "--"
				}
			},
			//数据 渲染
			getDateList() {
				this.versionArray.forEach((item,index)=>{
					if(this.indexNum === index){
						this.versionDataItem = item
					}
				})
				let callback = (data) => {
					this.dataList = data;
				}
				getDate(callback, this.relGroup, this.getDataItem.rid || this.initRid);
			},
			getVersionData() {
				 let callback = (data) => {
					this.versionArray = data;
					this.$nextTick(() => {
						this.$refs.versionSpecial && this.$refs.versionSpecial.map(item => {
							let data = item.dataset;
							if(data.currentitem ==='1'){
								this.initRid = data.rid
							}
						}) 
						if(this.isInit){
								this.getDateList()
							}
					})
				}
				getVersionDataList(callback, this.relGroup);
			},
			//新增
			add() {
				let params = this.getParams();
				let callback = data => {
					this.dataList = data;
					this.$refs.editModel.hideCover();
				}
				this.versionArray.forEach((item,index)=>{
					if(this.indexNum === index){
						this.versionDataItem = item
					}
				})
				madd(params, this.relGroup, callback,this.getDataItem.rid);
			},
			edit() {
				let params = this.getParams();
				let callback = data => {
					this.dataList = data;
					this.$refs.editModel.hideCover();
				}
				medit(params, this.relGroup, callback,this.getDataItem.rid);
			},
			deleteGoods(item) {
				let msg = '确定要删除吗？';
				let confirmFn = () => {
					let params = {
						rid: item.rid,
						storeCode: this.storeCode,
						relGroup: this.relGroup
					}
					let callback = data => {
						this.dataList = data;
					}
					deleteGoods(params, this.relGroup, callback,this.getDataItem.rid);
				}
				this.infoDialog(msg, confirmFn);
			},
			getParams() {
				var obj = {
					"url": this.selected
				}
				var str = JSON.stringify(obj);
				this.versionArray.forEach((item,index)=>{
					if(this.indexNum === index){
						this.versionDataItem = item
					}
				})
				if(this.uploadType == 'add') {
					var params = {
						publicityPicture: this.imgUrl,
						storeCode: this.storeCode,
						relGroup: this.relGroup,
						extendField: str,
						//添加版本下的rid
						resourceDateId: this.getDataItem.rid
					}
				} else if(this.uploadType == 'edit') {
					var params = {
						storeCode: this.storeCode,
						publicityPicture: this.imgUrl,
						rid: this.editItem.rid,
						relGroup: this.relGroup,
						extendField: str,
						resourceDateId: this.getDataItem.rid
					}
				}
				return params;
			},
			infoDialog(msg, confirmFn) {
				this.$refs.dialog.dialog({
					msg,
					confirmFn
				});
			},
			myGetTime(param) {
				if(param) {
					let date = new Date(param);
					let year = date.getFullYear();
					let month = checkTime(date.getMonth() + 1);
					let day = checkTime(date.getDate());
					let hour = date.getHours();
					let min = checkTime(date.getMinutes());
					let sec = checkTime(date.getSeconds());
					let str = '';
					let mHour = 0;
					if(0 < Number(hour) && Number(hour) < 12) {
						mHour = hour;
						str = '上午'
					} else {
						mHour = Number(hour) - 12;
						str = '下午'
					}

					function checkTime(i) {
						if(i < 10) {
							i = '0' + i;
						}
						return i;
					}
					return year + '/' + month + '/' + day + '  ' + str + ' ' + mHour + ':' + min;
				} else {
					return '';
				}
			},
			//点击新增按钮
			clickAdd() {
				if(this.indexNum===''){
					this.$refs.toast.toast("请先点击选择版本");
					return
				}
				if(!getCookie("sessionId")){
					this.$refs.toast.toast("登录失效，请重新登录");
					return
			    }
				if(this.dataList.length > 4) {
					this.$refs.toast.toast("此模块只能添加五条数据");
					return;
				}
				this.showModel();
				this.uploadType = 'add';
				this.valueArray = []
				this.selected = ""
				this.imgUrl = '';
				this.getBannerUrl = '';
				this.dataListSinger = {};
				this.ziyuanwei = '';
				this.$refs.bannerImg.deleteImg();
				console.log(this.imgUrl, this.getBannerUrl, '清除数据')
			},
			clickEdit(index, item) {
				console.log(item, '编辑')
				this.getBannerUrl = item.publicityPicture;
				this.dataListSinger = item;
				this.valueArray = JSON.parse(item.extendField).url.valueArray
				this.ziyuanwei = Number(index) + 1;
				this.showModel();
				this.editItem = item;
				this.uploadType = 'edit';
				this.imgUrl = item.image;
				this.selected =  JSON.parse(item.extendField).url
			},
			showModel() {
				this.$refs.editModel.showCover();
			},
			hideModel() {
				this.$refs.editModel.hideCover();
			},
			async upLoadImg() {
				let response = await this.$refs.bannerImg.upload();
				if(response.status === 0) {
					this.errorToast("图片上传失败");
					return;
				}
				if(this.uploadType == 'add') {
					if(response.status === 1) {
						this.imgUrl = response.data[0];
						this.add();
					}
				} else {
					if(response.status === 1) {
						this.imgUrl = response.data[0];
						this.edit();
					} else if(response.status === 2) {
						if(!this.getBannerUrl) {
							this.errorToast("请上传图片");
							return;
						} else {
							this.edit();
						}
					}
				}
			},
			errorToast(msg, duration = 1000) {
				this.$refs.toast.toast(msg, duration);
			},
			deleteImgCallback() {
				this.imgUrl = '';
			},
			//点击新增版本
			addVersion(){
				if(!getCookie("sessionId")){
					this.$refs.toast.toast("登录失效，请重新登录");
					return
				}
				//当点击新增的时候让版本类型变为'add'
				this.versionType = "add"
				this.$refs.versionModel.showCover();
				// this.versionArray = [];
				this.versionDataItem = {}
				this.startTime = "";
				this.endTime = ""
			},
			//点击提交发布按钮
			versionPublish(){
				//此处做校验
				if(!this.getDataItem.titleName) {
					this.$refs.toast.toast("版本名称不能为空");
					return;
				}
				if(!this.startTime) {
					this.$refs.toast.toast("生效时间不能为空");
					return;
				}
				if(!this.endTime) {
					this.$refs.toast.toast("失效时间不能为空");
					return;
				}
				if(this.endTime < this.startTime){
					this.$refs.toast.toast("失效时间不能早于生效时间");
					return;
				}
				if(this.endTime< new Date().getTime()){
					this.$refs.toast.toast("失效时间不能早于当前时间");
					return;
				}
				// if(){
				// 	this.$refs.toast.toast("版本时间有交叉");
				// 	return;
				// }
				this.addEditVersionFun();
			},
			//获取提交发布的时候参数
			getParamsVersion(){
				if(this.versionType == 'add') {
					var params = {
						storeCode: this.storeCode,
						relGroup: this.relGroup,
						titleName: this.getDataItem.titleName
					}
				}else if (this.versionType == 'edit'){
					var params = {
						storeCode: this.storeCode,
						relGroup: this.relGroup,
						titleName: this.getDataItem.titleName,
						rid:this.getDataItem.rid
					}
				}
				if (this.startTime) {
						let date = new Date(this.startTime);
						let startTmStr = `${date.getFullYear()}-${date.getMonth() + 1 > 9 ? date.getMonth() + 1:'0' + (date.getMonth() + 1)}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`
						params = Object.assign({}, params, {
							startTmStr: startTmStr,
					});
					} else {
						params = Object.assign({}, params, {
						startTmStr: "",
					});
				}
				//设置失效时间的参数
				if (this.endTime) {
						let date = new Date(this.endTime);
						let endTmStr = `${date.getFullYear()}-${date.getMonth() + 1 > 9 ? date.getMonth() + 1:'0' + (date.getMonth() + 1)}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`
						params = Object.assign({}, params, {
							endTmStr: endTmStr,
						});
					} else {
						params = Object.assign({}, params, {
							endTmStr: "",
						});
				}
				return params
			},
			//点击提交发布调用接口
			addEditVersionFun(){
				let params = this.getParamsVersion();
				let callback = data => {
					this.versionArray = data;
					this.$refs.versionModel.hideCover();
				}
				let errFn = data =>{
					this.$refs.toast.toast(data);
				}
				if(this.versionType == 'add'){
					addVersionRes(params, this.relGroup, callback,errFn);
				} else if(this.versionType == 'edit'){
					editVersionRes(params, this.relGroup, callback,errFn);
				}
			},
			//点击编辑版本
			editVersion(){	
				this.versionType = "edit"
				this.$refs.versionModel.showCover();
				this.versionArray.forEach((item,index)=>{
					if(this.indexNum === index){
						this.versionDataItem = item
					}
				})
				this.startTime = this.getDataItem.startTm
				this.endTime = this.getDataItem.endTm
			},
			//取消发布提交
			cancelVerionPub(){
				this.$refs.versionModel.hideCover();
			},
			//点击版本名称
			clickVersionName(item,index){
				this.indexNum = index;
				this.$store.commit('lxn/setclickVersionIndex',index);
				if(item.show===1){
					this.isGrayDis = true
				}else {
					this.isGrayDis = false
				}
			},
			//点击删除版本信息
			deleteVersion(){
				if(this.indexNum===''){
					this.$refs.toast.toast("请先点击选择版本");
					return
				}
				this.versionArray.forEach((item,index)=>{
					if(this.indexNum === index){
						this.versionDataItem = item
					}
				})
				let msg = '确定要删除这个版本吗？';
				let confirmFn = () => {
					let params = {
						rid: this.getDataItem.rid,
						storeCode: this.storeCode,
						relGroup: this.relGroup
					}
					let callback = data => {
						this.versionArray = data;
						// 当点击删除当前的这个版本时下面对应的数据一并删除
						this.dataList = []
					}
					deleteVersionRes(params, this.relGroup, callback)
				}
				this.infoDialog(msg, confirmFn);
			},
		},
		filters: {},
		created() {
			this.isInit = true;
		},
		mounted() {
			if(!getCookie("sessionId")){
				this.$refs.toast.toast("登录失效，请重新登录");
			}
			this.getVersionData()
			this.getShopCode();
		},
		watch: {
			relGroup(newVal) {
				this.getVersionData()
				this.getDateList();
				this.getShopCode();
			},
			indexNum(newVal){
				this.getDateList();
			}
		}
	}
</script>

<style scoped>
	.confimBtn {
		margin-left: 20px;
	}
	
	.grayBtn {
		display: inline-block;
	}
	.fabu-box {
		display: flex;
		justify-content: center;
		margin-top: 30px;
	}
	.mySelect {
		border: 1px solid #ddd;
		padding: 5px 5px;
		width: 50%;
		height: unset;
		margin-bottom: 10px;
	}
	
	.casor {
		cursor: not-allowed;
	}
	
	.FeaturedGoodsNew tr td:nth-child(2) {
		width: 80px;
		display: inline-block;
		height: 66px;
		overflow: hidden;
		line-height: 66px;
		border: none
	}
	
	.FeaturedGoodsNew tr td:nth-child(2) img {
		height: 66px;
	}
	.versionButtonGropu{
		margin-bottom:10px;
		text-align: left
	}
	.versionButtonGropu>div{
		display:inline-block;
		margin-left:20px;
	}
	.versionButtonGropu>div:nth-child(1){
		margin-left:0
	}
	.version-item{
		text-align: left;
		padding:10px 0px
	}
	.version-item.version-item-first input{
		display:inline-block;
		margin-left:10px;
	}
	.versionName{
		display:inline-block;
		margin:0 10px;
		border:1px solid #999;
		padding:0 15px;
		border-radius:5px
	}
	.versionName:nth-child(1){
		margin-left:12px
	}
	.versionBox{
		text-align: left;
		margin-bottom:20px;
	}
	.versionBg{
		background-color:cornflowerblue;
		transform: scale(1.3);
		border:1px solid cornflowerblue;
	}
	.versionBg span{
		color:#fff
	}
	.currentItem{
		background-color: brown !important;
		border:1px solid brown;
		color:#fff
	}
	.deleteSpan {
		display: inline-block;
		height: 28px;
		border: 1px solid #3876ae;
		width: 70px;
		font-size: 14px;
		background: #3876ae;
		color: #fff;
		line-height: 28px;
		border-radius: 3px;
		text-align: center;
	}
</style>